package com.senssun.blesample;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.senssun.blesample.util.ConstantBLEWIFI;
import com.senssun.blesample.util.WIFIUtils;
import com.senssun.blelib.BleManager;
import com.senssun.blelib.callback.BleNotifyCallback;
import com.senssun.blelib.callback.BleWriteCallback;
import com.senssun.blelib.data.BleDevice;
import com.senssun.blelib.exception.BleException;
import com.senssun.blelib.utils.HexUtil;

import java.util.UUID;

import static com.senssun.blesample.operation.OperationActivity.KEY_DATA;

public class BleWifiActivity extends AppCompatActivity {
    public final UUID SERVICE_UUID = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");
    public final UUID CHARACTERISTIC_WRITE_UUID = UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb");
    public final UUID CHARACTERISTIC_NOTIFY_UUID = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb");

    private BluetoothGattCharacteristic mWriteCharacteristic; //写出GATT,char
    private BluetoothGattCharacteristic mNOTIFYCharacteristic;
    EditText etServer, etPort, etWiFi, etPw, etDevice, etCheck, etOta;
    Button btServer, btWifi, btDevice, btStatus, btOta;
    TextView tvContent;
    private BleDevice bleDevice;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ble_wifi);

        initView();
        initData();
    }

    private void initView() {
        etServer = findViewById(R.id.et_server);
        etPort = findViewById(R.id.et_port);
        etWiFi = findViewById(R.id.et_wifi);
        etPw = findViewById(R.id.et_pw);
        etDevice = findViewById(R.id.et_device);
        btServer = findViewById(R.id.bt_server);
        btWifi = findViewById(R.id.bt_wifi);
        btDevice = findViewById(R.id.bt_device);
        btStatus = findViewById(R.id.bt_check);
        tvContent = findViewById(R.id.tv_content);
        etCheck = findViewById(R.id.et_check);
        etOta = findViewById(R.id.et_ota);
        btOta = findViewById(R.id.bt_ota);
        tvContent.setMovementMethod(new ScrollingMovementMethod());

        btWifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String temp = getNameAndPwHex();
                sendCommand(temp);
            }
        });

        btServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String temp = getServerAndPortHex();
                sendCommand(temp);
            }
        });
        btDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String temp = getDeviceID();
                sendCommand(temp);
            }
        });
        btStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etCheck.getText().toString())) {
                    showTip("指令不完整");
                    return;
                }
                String temp = WIFIUtils.buildCommand("cc" + etCheck.getText().toString(), "00");
                sendCommand(temp);
            }
        });
        btOta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String temp = getOtaIP();
                sendCommand(temp);

            }
        });
    }

    private void sendCommand(String temp) {
        if (temp == null) {
            showTip("指令不完整");
            return;
        }
        doSendCommand(temp);
    }

    private void doSendCommand(String command) {
        BleManager.getInstance().write(
                bleDevice,
                mWriteCharacteristic.getService().getUuid().toString(),
                mWriteCharacteristic.getUuid().toString(),
                HexUtil.hexStringToBytes(command),
                new BleWriteCallback() {

                    @Override
                    public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                addText(tvContent, "write success"
                                        + "  Write: " + HexUtil.formatHexString(justWrite, true));
                            }
                        });
                    }

                    @Override
                    public void onWriteFailure(final BleException exception) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                addText(tvContent, exception.toString());
                            }
                        });
                    }
                });
    }


    private void initData() {
        bleDevice = getIntent().getParcelableExtra(KEY_DATA);
        if (bleDevice == null)
            finish();
        BluetoothGatt gatt = BleManager.getInstance().getBluetoothGatt(bleDevice);
        BluetoothGattService service = gatt.getService(SERVICE_UUID);
        if (service != null) {
            mWriteCharacteristic = service.getCharacteristic(CHARACTERISTIC_WRITE_UUID);
            mNOTIFYCharacteristic = service.getCharacteristic(CHARACTERISTIC_NOTIFY_UUID);
        }
        if (mNOTIFYCharacteristic != null) {
            BleManager.getInstance().notify(
                    bleDevice,
                    mNOTIFYCharacteristic.getService().getUuid().toString(),
                    mNOTIFYCharacteristic.getUuid().toString(),
                    new BleNotifyCallback() {

                        @Override
                        public void onNotifySuccess() {

                        }

                        @Override
                        public void onNotifyFailure(final BleException exception) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    addText(tvContent, exception.toString());
                                }
                            });
                        }

                        @Override
                        public void onCharacteristicChanged(final byte[] data) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    addText(tvContent, HexUtil.formatHexString(data, true));
                                }
                            });
                        }


                    });
        }
    }



    private void addText(TextView textView, String content) {
        textView.append(content);
        textView.append("\n");
        int offset = textView.getLineCount() * textView.getLineHeight();
        if (offset > textView.getHeight()) {
            textView.scrollTo(0, offset - textView.getHeight());
        }
    }


    private String getServerAndPortHex() {
        StringBuffer stringBuffer = new StringBuffer();
        String server = etServer.getText().toString();
        String port = etPort.getText().toString();
        if (TextUtils.isEmpty(server) || TextUtils.isEmpty(port)) {
            return null;
        }
        stringBuffer.append(WIFIUtils.convertAsciiToHex(server));
        stringBuffer.append(Integer.toHexString(Integer.parseInt(port)));
        String temp = stringBuffer.toString();
        temp = WIFIUtils.buildCommand(ConstantBLEWIFI.SET_SERVER_PORT, temp);
        Log.d("Ble_command", temp);
        return temp;
    }


    private String getOtaIP() {
        String ota = etOta.getText().toString();
        if (TextUtils.isEmpty(ota)) {
            return null;
        }
        String temp = WIFIUtils.convertAsciiToHex(ota);
        temp = WIFIUtils.buildCommand(ConstantBLEWIFI.SET_WIFI_OTA, temp);
        Log.d("Ble_command", temp);
        return temp;
    }

    private String getDeviceID() {
        String device = etDevice.getText().toString();
        if (TextUtils.isEmpty(device)) {
            return null;
        }
        String temp = device;
        temp = WIFIUtils.buildCommand(ConstantBLEWIFI.SET_DEVICE_ID, temp);
        Log.d("Ble_command", temp);
        return temp;
    }


    private String getNameAndPwHex() {//WiFi账号在前，密码在后，格式为：格式为：[长度][内容][长度][内容] 一字节长度不包含本身一字节
        StringBuffer stringBuffer = new StringBuffer();
        String name = etWiFi.getText().toString();
        String pw = etPw.getText().toString();
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pw)) {
            return null;
        }
        stringBuffer.append(getLen(name));
        stringBuffer.append(WIFIUtils.convertAsciiToHex(name));
        stringBuffer.append(getLen(pw));
        stringBuffer.append(WIFIUtils.convertAsciiToHex(pw));
        String temp = stringBuffer.toString();
        temp = WIFIUtils.buildCommand(ConstantBLEWIFI.SET_WIFI_CONFIG, temp);
        Log.d("Ble_command", temp);
        return temp;
    }

    private String getLen(String name) {
        int nameLen = name.length();
        String len = Integer.toHexString(nameLen);
        if (len.length() == 1) {
            len = "0" + len;
        }
        return len;
    }

    void showTip(String str) {
        Toast.makeText(BleWifiActivity.this, str, Toast.LENGTH_LONG).show();
    }
}
